 'use client'

import { motion } from 'framer-motion'
import { useState, useEffect, useRef } from 'react'
import { BookOpen, Heart, Share2, Download } from 'lucide-react'
import html2canvas from 'html2canvas'

interface Verse {
  id: number
  book: string
  chapter: number
  verse: number
  content: string
  translation: string
  keywords: string[]
  background: string | string[]
  mood: string
}

interface VerseCardProps {
  verse: Verse
  isFlipping: boolean
  onSave?: () => void
  onShare?: () => void
  onDownload?: () => void
}

const backgroundImages = {
  // 创造与宇宙主题
  'cosmic_creation.jpg': 'https://images.unsplash.com/photo-1446776653964-20c1d3a81b06?w=800&h=600&fit=crop',
  'universe_birth.jpg': 'https://images.unsplash.com/photo-1502134249126-9f3755a50d78?w=800&h=600&fit=crop',
  'starry_sky.jpg': 'https://images.unsplash.com/photo-1419242902214-272b3f66ee7a?w=800&h=600&fit=crop',
  'genesis_beginning.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'celestial_view.jpg': 'https://images.unsplash.com/photo-1444927714506-8492d94b5ba0?w=800&h=600&fit=crop',
  
  // 光明与希望主题
  'divine_light_burst.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'golden_sunrise.jpg': 'https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?w=800&h=600&fit=crop',
  'light_breaking_darkness.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'heavenly_glow.jpg': 'https://images.unsplash.com/photo-1470252649378-9c29740c9fa8?w=800&h=600&fit=crop',
  'radiant_dawn.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  
  // 自然与生命主题
  'lush_green_meadow.jpg': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=800&h=600&fit=crop',
  'fruit_trees_orchard.jpg': 'https://images.unsplash.com/photo-1560493676-04071c5f467b?w=800&h=600&fit=crop',
  'peaceful_landscape.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'beautiful_garden.jpg': 'https://images.unsplash.com/photo-1416879595882-3373a0480b5b?w=800&h=600&fit=crop',
  'spring_blossoms.jpg': 'https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop',
  
  // 水景主题
  'ocean_waves.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  'peaceful_waters.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'flowing_river.jpg': 'https://images.unsplash.com/photo-1515694346937-94d85e41e6f0?w=800&h=600&fit=crop',
  'crystal_lake.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  'waterfall_power.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  
  // 山峰与力量主题
  'mountain_strength.jpg': 'https://images.unsplash.com/photo-1464822759844-d150baec0494?w=800&h=600&fit=crop',
  'mighty_fortress.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'alpine_majesty.jpg': 'https://images.unsplash.com/photo-1464822759844-d150baec0494?w=800&h=600&fit=crop',
  'rocky_peaks.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'snow_mountains.jpg': 'https://images.unsplash.com/photo-1464822759844-d150baec0494?w=800&h=600&fit=crop',
  
  // 动物与生命主题
  'soaring_eagle.jpg': 'https://images.unsplash.com/photo-1551522435-a13afa10f103?w=800&h=600&fit=crop',
  'wildlife_harmony.jpg': 'https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=800&h=600&fit=crop',
  'birds_flight.jpg': 'https://images.unsplash.com/photo-1551522435-a13afa10f103?w=800&h=600&fit=crop',
  'ocean_life.jpg': 'https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=800&h=600&fit=crop',
  'butterfly_garden.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  
  // 人文与神圣主题
  'human_silhouette_divine.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'family_creation.jpg': 'https://images.unsplash.com/photo-1511895426328-dc8714191300?w=800&h=600&fit=crop',
  'divine_reflection.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'sacred_humanity.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'people_blessing.jpg': 'https://images.unsplash.com/photo-1511895426328-dc8714191300?w=800&h=600&fit=crop',
  
  // 天堂与乐园主题
  'paradise_garden.jpg': 'https://images.unsplash.com/photo-1416879595882-3373a0480b5b?w=800&h=600&fit=crop',
  'eden_beauty.jpg': 'https://images.unsplash.com/photo-1416879595882-3373a0480b5b?w=800&h=600&fit=crop',
  'perfect_world.jpg': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=800&h=600&fit=crop',
  'sacred_trees.jpg': 'https://images.unsplash.com/photo-1560493676-04071c5f467b?w=800&h=600&fit=crop',
  'blissful_landscape.jpg': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=800&h=600&fit=crop',
  
  // 祝福与恩典主题
  'divine_blessing.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'golden_light_blessing.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'heavenly_favor.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'abundant_grace.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'sacred_benediction.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  
  // 引导与智慧主题
  'guiding_light.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'wise_path.jpg': 'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?w=800&h=600&fit=crop',
  'shepherd_path.jpg': 'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?w=800&h=600&fit=crop',
  'divine_direction.jpg': 'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?w=800&h=600&fit=crop',
  'wisdom_light.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  
  // 爱与慈爱主题
  'heart_light.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'divine_love_glow.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'heart_warmth.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'compassionate_light.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'tender_mercy.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  
  // 信心与成长主题
  'faithful_journey.jpg': 'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?w=800&h=600&fit=crop',
  'trust_path.jpg': 'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?w=800&h=600&fit=crop',
  'believing_heart.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'spiritual_growth.jpg': 'https://images.unsplash.com/photo-1560493676-04071c5f467b?w=800&h=600&fit=crop',
  'faith_mountain.jpg': 'https://images.unsplash.com/photo-1464822759844-d150baec0494?w=800&h=600&fit=crop',
  
  // 希望与未来主题
  'hope_sunrise.jpg': 'https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?w=800&h=600&fit=crop',
  'bright_future.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'optimistic_dawn.jpg': 'https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?w=800&h=600&fit=crop',
  'renewed_spirit.jpg': 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?w=800&h=600&fit=crop',
  'joyful_anticipation.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  
  // 平安与宁静主题
  'calm_lake.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  'serene_meadow.jpg': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=800&h=600&fit=crop',
  'tranquil_scene.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  'calm_spirit.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  'divine_stillness.jpg': 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=800&h=600&fit=crop',
  
  // 喜乐与庆祝主题
  'golden_field.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'joyful_celebration.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'radiant_happiness.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  'festive_gathering.jpg': 'https://images.unsplash.com/photo-1511895426328-dc8714191300?w=800&h=600&fit=crop',
  'abundant_joy.jpg': 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=800&h=600&fit=crop',
  
  // 默认备用图片
  'warm_sunset.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
  'peaceful_meadow.jpg': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=800&h=600&fit=crop',
  'trinity_light.jpg': 'https://images.unsplash.com/photo-1419242902214-272b3f66ee7a?w=800&h=600&fit=crop',
  'heavenly_peace.jpg': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop'
}

const moodColors = {
  // 中文情绪对应的渐变色
  '庄严神圣': 'from-purple-500/30 to-indigo-600/30',
  '充满希望': 'from-yellow-400/30 to-orange-500/30',
  '温暖慈爱': 'from-pink-400/30 to-rose-500/30',
  '平静安详': 'from-blue-400/30 to-cyan-500/30',
  '喜悦欢欣': 'from-yellow-300/30 to-amber-400/30',
  '坚强有力': 'from-purple-600/30 to-violet-700/30',
  '智慧深邃': 'from-indigo-500/30 to-blue-600/30',
  '温柔安慰': 'from-emerald-400/30 to-teal-500/30',
  '蒙福感恩': 'from-amber-400/30 to-yellow-500/30',
  '敬虔崇拜': 'from-violet-500/30 to-purple-600/30',
  '平静祥和': 'from-green-400/30 to-emerald-500/30',
  
  // 英文情绪（向后兼容）
  warm: 'from-orange-400/30 to-red-500/30',
  peaceful: 'from-green-400/30 to-blue-500/30',
  powerful: 'from-purple-500/30 to-indigo-600/30',
  restful: 'from-blue-400/30 to-cyan-500/30',
  hopeful: 'from-yellow-400/30 to-orange-500/30',
  uplifting: 'from-sky-400/30 to-blue-500/30',
  loving: 'from-pink-400/30 to-rose-500/30',
  contemplative: 'from-indigo-400/30 to-purple-500/30',
  profound: 'from-violet-400/30 to-purple-500/30',
  comforting: 'from-emerald-400/30 to-teal-500/30',
  majestic: 'from-purple-500/30 to-indigo-600/30',
  joyful: 'from-yellow-400/30 to-amber-500/30',
  sacred: 'from-violet-500/30 to-purple-600/30',
  satisfied: 'from-green-500/30 to-emerald-600/30',
  empowering: 'from-orange-500/30 to-red-600/30',
  grateful: 'from-amber-400/30 to-yellow-500/30',
  mysterious: 'from-indigo-600/30 to-purple-700/30',
  blissful: 'from-pink-300/30 to-rose-400/30',
  gentle: 'from-cyan-300/30 to-blue-400/30',
  reflective: 'from-slate-400/30 to-gray-500/30',
  anticipatory: 'from-teal-400/30 to-cyan-500/30'
}

export default function VerseCard({ verse, isFlipping, onSave, onShare, onDownload }: VerseCardProps) {
  const [imageLoaded, setImageLoaded] = useState(false)
  const [showText, setShowText] = useState(false)
  const [backgroundUrl, setBackgroundUrl] = useState('')
  const cardRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!isFlipping) {
      const timer = setTimeout(() => setShowText(true), 800)
      return () => clearTimeout(timer)
    } else {
      setShowText(false)
    }
  }, [isFlipping])

  // 在客户端设置背景图片，避免水合错误
  useEffect(() => {
    const getBackgroundUrl = () => {
      if (Array.isArray(verse.background)) {
        const randomImage = verse.background[Math.floor(Math.random() * verse.background.length)]
        return backgroundImages[randomImage as keyof typeof backgroundImages] || backgroundImages['warm_sunset.jpg']
      } else {
        return backgroundImages[verse.background as keyof typeof backgroundImages] || backgroundImages['warm_sunset.jpg']
      }
    }
    setBackgroundUrl(getBackgroundUrl())
  }, [verse.background])
  const moodGradient = moodColors[verse.mood as keyof typeof moodColors] || moodColors.warm

  // 下载卡片为图片
  const handleDownload = async () => {
    if (!cardRef.current) return
    
    try {
      // 临时隐藏操作按钮
      const buttons = cardRef.current.querySelector('.action-buttons') as HTMLElement
      if (buttons) buttons.style.display = 'none'
      
      const canvas = await html2canvas(cardRef.current, {
        backgroundColor: null,
        scale: 2, // 提高图片质量
        useCORS: true,
        allowTaint: true,
        width: cardRef.current.offsetWidth,
        height: cardRef.current.offsetHeight,
      })
      
      // 恢复操作按钮显示
      if (buttons) buttons.style.display = 'flex'
      
      // 创建下载链接
      const link = document.createElement('a')
      link.download = `经文卡片-${verse.book}${verse.chapter}_${verse.verse}.png`
      link.href = canvas.toDataURL('image/png')
      link.click()
      
      if (onDownload) onDownload()
    } catch (error) {
      console.error('下载失败:', error)
      alert('下载失败，请重试')
    }
  }

  return (
    <motion.div
      className="relative w-full max-w-md mx-auto"
      initial={{ scale: 0.8, opacity: 0 }}
      animate={{ 
        scale: isFlipping ? [1, 1.1, 1] : 1, 
        opacity: 1,
        rotateY: isFlipping ? [0, 90, 0] : 0
      }}
      transition={{ 
        duration: isFlipping ? 1.5 : 0.8,
        ease: "easeInOut"
      }}
    >
      {/* 卡片堆叠效果背景 */}
      <div className="absolute inset-0 bg-white/10 rounded-2xl transform rotate-2 scale-95 blur-sm"></div>
      <div className="absolute inset-0 bg-white/5 rounded-2xl transform -rotate-1 scale-98 blur-sm"></div>
      
      {/* 主卡片 */}
      <div id="verse-card" ref={cardRef} className="relative bg-white rounded-2xl shadow-2xl overflow-hidden card-3d glow-effect">
        {/* 背景图片 */}
        <div className="absolute inset-0">
          <img
            src={backgroundUrl}
            crossOrigin="anonymous"
            alt="背景"
            className={`w-full h-full object-cover transition-opacity duration-1000 ${
              imageLoaded ? 'opacity-100' : 'opacity-0'
            }`}
            onLoad={() => setImageLoaded(true)}
          />
          <div className={`absolute inset-0 bg-gradient-to-br ${moodGradient}`}></div>
          <div className="absolute inset-0 bg-black/20"></div>
        </div>

        {/* 内容区域 */}
        <div className="relative z-10 p-8 h-96 flex flex-col justify-between text-white">
          {/* 顶部装饰 */}
          <motion.div 
            className="flex items-center justify-center mb-4"
            initial={{ y: -20, opacity: 0 }}
            animate={{ y: 0, opacity: showText ? 1 : 0 }}
            transition={{ delay: 0.3 }}
          >
            <BookOpen className="w-8 h-8 text-gold-300" />
          </motion.div>

          {/* 经文内容 */}
          <motion.div 
            className="flex-1 flex items-center justify-center text-center"
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: showText ? 1 : 0 }}
            transition={{ delay: 0.6 }}
          >
            <p className="text-lg md:text-xl font-serif leading-relaxed text-shadow-lg">
              {verse.content}
            </p>
          </motion.div>

          {/* 经文出处 */}
          <motion.div 
            className="text-center"
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: showText ? 1 : 0 }}
            transition={{ delay: 0.9 }}
          >
            <p className="text-gold-200 font-medium text-lg">
              {verse.book} {verse.chapter}:{verse.verse}
            </p>
            <p className="text-white/70 text-sm mt-1">
              {verse.translation}
            </p>
          </motion.div>

          {/* 关键词标签 */}
          <motion.div 
            className="flex flex-wrap justify-center gap-2 mt-4"
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: showText ? 1 : 0 }}
            transition={{ delay: 1.2 }}
          >
            {verse.keywords.map((keyword, index) => (
              <span
                key={index}
                className="inline-block text-center h-[32px] leading-[32px] px-4 bg-white/20 backdrop-blur-sm rounded-full text-sm font-medium whitespace-nowrap"
              >
                {keyword}
              </span>
            ))}
          </motion.div>
        </div>

        {/* 操作按钮已移除 */}
      </div>
    </motion.div>
  )
}